import useRequest from "@/api/useRequest";
import {IPage} from "@/interface/modules/system";

export class storyController {

  static getStoryBoardView(storyId: string, status: string): Promise<any> {
    return useRequest({
      url: "/story/getStoryBoardView/" + storyId +"/" + status,
      method: "get"
    })
  }
  static privilegeKeyWord(data: any): Promise<any> {
    return useRequest({
      url: "/story/privilegeKeyWord",
      method: "post",
      data
    })
  }
  static getStoryList(data: any, pagination?: IPage): Promise<any> {
    return useRequest({
      url: "/story/getStoryList",
      method: "post",
      params: pagination,
      data
    })
  }

  static rewrite(data: any): Promise<any> {
    return useRequest({
      url: '/story/rewrite',
      method: 'post',
      data
    })
  }

  static deleteStory(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/deleteStory?id=" + storyId,
      method: "get"
    })
  }

  static getStoryById(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/getStory?id=" + storyId,
      method: "get"
    })
  }

  static initJianYingDraft(data: any): Promise<any> {
    return useRequest({
      url: "/story/initJianYinDraft",
      method: "post",
      data
    })
  }


  static initStoryBoards(data: any): Promise<any> {
    return useRequest({
      url: "/story/initStoryBoards",
      method: "post",
      data
    })
  }

  static summary(data: any): Promise<any> {
    return useRequest({
      url: "/story/storySummary",
      method: "post",
      data
    })
  }

  static saveSummary(data:any):Promise<any>{
    return useRequest({
      url: "/story/saveSummary",
      method: "post",
      data
    })
  }

  static addStory(data: any): Promise<any> {
    return useRequest({
      url: "/story/addStoryChapter",
      method: "post",
      data
    })
  }

  static updateStory(data: any): Promise<any> {
    return useRequest({
      url: "/story/updateStory",
      method: "post",
      data
    })
  }

  static saveStoryConfig(data: any): Promise<any> {
    return useRequest({
      url: "/story/saveStoryPaintConfig",
      method: "post",
      data
    })
  }

  static checkStorySetting(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/checkStorySetting?storyId=" + storyId,
      method: "get"
    })
  }

  static checkStoryBoardPrompt(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/checkStoryBoardPrompt?storyId=" + storyId,
      method: "get"
    })
  }

  static getStoryPaintConfig(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/getStoryPaintConfigByChapterId?chapterId=" + storyId,
      method: "get"
    })
  }

  static submitVideoCreate(data: any): Promise<any> {
    return useRequest({
      url: "/story/exportVideoTask",
      method: "post",
      data
    })
  }

  static importStoryBoardByTxt(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/importStoryBoardByTxt",
      method: "post",
      data
    })
  }

  static getStoryBoardByChapterId(chapterId: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/getStoryBoardByChapterId?chapterId=" + chapterId,
      method: "get"
    })
  }

  static getStoryScheduleByChapterId(chapterId: string, dataType:string): Promise<any> {
    return useRequest({
      url: "/story/getStoryScheduleByChapterId?chapterId=" + chapterId + "&dataType=" + dataType,
      method: "get"
    })
  }

  static getVideoText(data:any): Promise<any>{
    return useRequest({
      url: "/story/getVideoText",
      method: "post",
      params: data
    })
  }

  static getStoryBoardByNovel(data:any): Promise<any>{
    return useRequest({
      url: "/story/getStoryBoardByNovel",
      method: "post",
      params: data
    })
  }


  static getWhisperText(storyId:string): Promise<any>{
    return useRequest({
      url: "/story/getWhisperText?storyId=" + storyId,
      method: "get"
    })
  }


  static getKeyWordByContent(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/getKeyWordByContent",
      method: "post",
      data
    })
  }

  static getImageDescription(data: any, extractPlan: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/keywordExtract",
      method: "post",
      params: {extractPlanCode: extractPlan},
      data
    })
  }

  static async reTtsStoryBoard(storyBoardId: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/reTtsStoryBoard?storyBoardId=" + storyBoardId,
      method: "get"
    })
  }

  static updatePrompt(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/updatePrompt",
      method: "post",
      data
    })
  }

  static updatePic(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/updatePic",
      method: "post",
      data
    })
  }

  static text2Img(data: any): Promise<any> {
    return useRequest({
      url: "/storyBoard/submitTxt2ImgTask",
      method: "post",
      data
    })
  }

  static sentenseBreak(data: any): Promise<any> {
    return useRequest({
      url: "/story/sentenseBreak",
      method: "post",
      data
    })
  }



  static startStoryBatchTask(data: any): Promise<any> {
    return useRequest({
      url: "/story/batchOperation",
      method: "post",
      data
    })
  }


  static startStoryTask(chapterId: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/initChapterTask?chapterId=" + chapterId,
      method: "get"
    })
  }


  static checkVideoRepaintStoryBoard(storyId: string,step:string): Promise<any> {
    return useRequest({
      url: "/story/checkVideoRepaintStoryBoard?storyId=" + storyId+"&step="+ step,
      method: "get"
    })
  }

  static getStoryMediaInfo(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/getStoryMediaInfo?storyId=" + storyId,
      method: "get"
    })
  }

  static listVoiceActors(storyId:string): Promise<any> {
    return useRequest({
      url: "/story/getVoiceListByStoryId?storyId=" + storyId,
      method: "get"
    })
  }

  static addExtraAudioFile(storyId:string,audioFileId:string): Promise<any> {
    return useRequest({
      url:'/story/addExtraAudio?storyId='+storyId+'&audioId='+audioFileId,
      method:'get'
    })
  }

  static matchAudio(storyId:string): Promise<any> {
    return useRequest({
      url:'/story/matchAudio?storyId='+storyId,
      method:'get'
    })
  }

  static matchTimeZone(storyId:string): Promise<any> {
    return useRequest({
      url:'/story/matchTimeZone?storyId='+storyId,
      method:'get'
    })
  }

  static getStorySentences(storyId:string): Promise<any> {
    return useRequest({
      url:'/story/getStorySentences?storyId='+storyId,
      method:'get'
    })
  }
  static getSetUpInfo(storyId:string): Promise<any> {
    return useRequest({
      url:'/story/getSetUpOption?storyId='+storyId,
      method:'get'
    })
  }

  static batchChosePic(data: any): Promise<any> {
    return useRequest({
      url: "/story/batchChosePic",
      method: "post",
      data
    })
  }



  static async batchInterrogate(data:any, timeoutMs: number,taskStatus:any): Promise<any> {
    // 发送任务提交请求
    const response = await useRequest({
      url: "/story/batchInterrogate",
      method: "post",
      data
    });
    if (response.code != 200) {
      return {
        taskStatus: "FAILED",
        failReason: response.data
      }
    }
    const taskId = data.storyId
    let pollingInterval: number | undefined;
    let polling = true; // 添加一个轮询标志变量
    // @ts-ignore
    const pollTaskStatus = async () => {
      if (!polling) {
        // 如果轮询被标志为停止，则返回 null
        return null;
      }
      // 发送任务状态检查请求
      const statusResponse = await useRequest({
        url: "/story/getBatchInterrogateLog?storyId=" + taskId ,
        method: "get",
      });
      console.log('statusResponse',statusResponse)
      const status = statusResponse.code;
      console.log("status", status);
      const numMap = statusResponse.data
      console.log('numMap',numMap)
      const totalNum = numMap.totalNum
      const txtNum = numMap.txtNum
      const failureNum = numMap.failureNum
      let isEnd = numMap.isEnd
      if (txtNum == totalNum){
        isEnd = 1
      }
      if (status == 200 && isEnd == 0 ) {
        taskStatus.value.successNum = txtNum
        taskStatus.value.totalNum = totalNum
        taskStatus.value.failNum = failureNum
        // 继续轮询
        await new Promise(resolve => setTimeout(resolve, 2000)); // 2S查询一次
        return pollTaskStatus(); // 继续轮询
      } else {
        if (status == 200){
          taskStatus.value.successNum = txtNum
          taskStatus.value.totalNum = totalNum
          taskStatus.value.failNum = failureNum
        }
        clearInterval(pollingInterval);
        return statusResponse;
      }
    };
    // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
    return await Promise.race([
      pollTaskStatus(),
      new Promise((_, reject) => {
        setTimeout(() => {
          clearInterval(pollingInterval)
          polling = false
          reject( {
            taskStatus: "FAILED",
            message: '任务超时啦！'
          });
        }, timeoutMs);
      }),
    ]);
  }


  // static batchInterrogate(data: any): Promise<any> {
  //   return useRequest({
  //     url: "/story/batchInterrogate",
  //     method: "post",
  //     data
  //   })
  // }

  static getStoryStep(storyId:string): Promise<any> {
    return useRequest({
      url:'/story/getStep?storyId='+storyId,
      method:'get'
    })
  }

  static async removeWaterMarkerTask(data: any, timeoutMs: number, loading:any, progressModal: any,totalNum: any, finshNum: any): Promise<any> {
    try {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/story/batchCleanupWaterMarker",
        method: "post",
        data,
      });
      const taskId = response.data.result;
      let pollingInterval;
      let polling = true; // 添加一个轮询标志变量
      const pollTaskStatus = async () => {
        console.log('pollTaskStatus{}检查状态')
        try {
          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/video/getImageRemoveWaterMarkerLog?taskId=" + taskId,
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          console.log("status", status);
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            if(status === "IN_PROGRESS"){
              if(progressModal){
                loading.value = false
                progressModal.value = true
              }
            }
            if(statusResponse.data.taskLog.totalNum){
              totalNum.value = statusResponse.data.taskLog.totalNum
              finshNum.value = statusResponse.data.taskLog.finishNum
            }
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            if (status === "SUCCESS") {
              console.log(statusResponse);
              // 返回任务制作成功的结果
              return statusResponse.data;
            } else {
              // 返回任务制作失败的结果
              throw new Error("任务制作失败");
            }
          }
        } catch (error) {
          throw new Error("任务状态检查失败");
        }
      };

      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      const result = await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
      console.log('result:{}',result)
      return result;
    } catch (error) {
      console.log(error);
      throw new Error("提交任务失败");
    }
  }

  static matchCharacter(storyId:string): Promise<any> {
    return useRequest({
      url: "/story/matchCharacter?storyId="+storyId,
      method: "get"
    })
  }


  static getVoiceTextNoPicker(storyId:string): Promise<any> {
    return useRequest({
      url: "/story/getVoiceTextNoPicker?storyId="+storyId,
      method: "get"
    })
  }

  static getStoryBoardList(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/getStoryBoardList?storyId="+storyId,
      method: "get"
    })
  }

  static reCatchImage(storyId: string): Promise<any> {
    return useRequest({
      url: "/story/reCatchImage/"+storyId,
      method: "get"
    })
  }
}

